package de.fuberlin.inf.alp2;

public class RingBuffer {
	private Object[] queue;
	private int first;
	private int last;
	
	public RingBuffer(final int size) {
		this.queue = new Object[size];
	}
	
	public void enqueue(Object obj) throws Exception {
		if (this.isEmpty())
			this.first = this.last = 0;
		else if (this.isFull())
			throw new Exception("Queue is already full");
		else
			this.last = this.next(this.last);
		this.queue[this.last] = obj;
	}
	
	public Object dequeue() throws Exception {
		if (this.isEmpty())
			throw new Exception("Queue is empty");
		Object returnValue = this.queue[this.first];
		this.queue[this.first] = null;
		this.first = this.next(this.first);
		return returnValue;
	}
	
	public boolean isEmpty() {
		return (this.queue[this.first] == null);
	}
	
	public boolean isFull() {
		return (this.queue[this.next(last)] != null);
	}

	private int next(int index) {
		return ((++index) >= this.queue.length) ? 0 : index;
	}
}
